/*
 * (c) Copyright 2014 Hewlett-Packard Development Company, L.P. All rights reserved.
 */
package com.hp.snap.gr.cmd;

import java.util.concurrent.CyclicBarrier;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hp.snap.gr.utils.Constants;
import com.hp.snap.gr.utils.eium.JMXClientUtils;

/**
 * @since 3.2
 * @author Yang, Lin
 * 
 */
public class GetStartSessionServerStatusCMD {

    private static Logger logger = LoggerFactory.getLogger(GetStartSessionServerStatusCMD.class);
    private static final String SS_ACTIVE = "ACTIVE";
    private static int countNum = 0;
    static JSONArray results;
    static long timeoutSeconds=120;

    

    /**
     * <b>input</b>
     * <p>
     * args[0]: JSON refer to gr-manager/src/main/artifacts/session_server/snap-status.sh
     * 
     * <pre>
     * {"results":[{"session_server":"STUDIO/snap460c03.chn.hp.com/SNAPStudio1","state":"Stopped"},{"session_server":"STUDIO/snap460c06.chn.hp.com/SNAPStudio2","state":"Stopped"}]}
     * </pre>
     * 
     * <b>output</b>
     * <p>
     * Constants.CONSOLE.info() add server_status and biz_service_status for each session server
     * 
     * <pre>
     * {"results":[{"session_server":"STUDIO/snap460c03.chn.hp.com/SNAPStudio1","server_status":"ACTIVE"},{"session_server":"STUDIO/snap460c06.chn.hp.com/SNAPStudio2","server_status":"IDEL"}]}
     * </pre>
     * 
     * @param args
     * @throws Exception
     * 
     */
    public static void main(String[] args) {
        try {
            GetStartSessionServerStatusCMD object = new GetStartSessionServerStatusCMD();
            JSONObject inputSS =  new JSONObject(args[0]);
            String output = object.main0(inputSS, Long.parseLong(args[1]));
            int len = new JSONObject(args[0]).getJSONArray("results").length();
            
            while (countNum < len) {
                Thread.sleep(2000);
            }
            // output
            if(logger.isDebugEnabled()){
                logger.debug("The getStartSession server output is:{}", inputSS.toString());
            }
            
            Constants.CONSOLE.info(inputSS.toString());
        } catch (Exception e) {
            if (logger.isTraceEnabled()) {
                logger.trace("Get session server status is failed!", e);
            }

            // output
            Constants.CONSOLE.info(args[0]);
            System.exit(1);
        } finally {
            try {
                JMXClientUtils.destroy();
            } catch (Exception e) {
                if (logger.isTraceEnabled()) {
                    logger.trace("Destroying JMX connection is failed!", e);
                }
            }
        }
    }

    private String main0(JSONObject input, long timeout) throws Exception {
        timeoutSeconds = timeout;
        logger.debug("The timeout seconds is:{}",timeoutSeconds);
         results = input.getJSONArray("results");

        if (results.length() < 1) {
            return input.toString();
        }

        for (int ii = 0, nn = results.length(); ii < nn; ii++) {
            JSONObject ssRow = results.getJSONObject(ii);

            StartSessionServerStatus object = new StartSessionServerStatus(ssRow);
            object.start();
        }

        return input.toString();
    }

    class StartSessionServerStatus extends Thread {

        private JSONObject ssRow;

        public StartSessionServerStatus(JSONObject ssRow) {
            this.ssRow = ssRow;
        }

        public void run() {
            String session_server = "";
            long _timeCount = 0;
            try {
                session_server = ssRow.getString("session_server");
            } catch (JSONException e1) {
                logger.info("Get session server is failed!", e1);
            }
            String[] session_server_split = StringUtils.split(session_server, "/");
            String hostname = session_server_split[1];
            String session_server_name = session_server_split[2];

            // server_status
            String mbean_server_status = new StringBuilder().append(hostname).append("/").append(session_server_name)
                    .append("/").append("ATOM:type=Server,name=ATOM Server").toString();
            String attribute_server_status = "Status";

            String ss_status = "";
            while (true) {
                try {
                    Thread.sleep(5000);
                    _timeCount = _timeCount + 5;
                    if(logger.isDebugEnabled())
                          logger.debug("The timeout count is:{} in the {}",new Object[]{_timeCount, session_server_name});
                    if (_timeCount > timeoutSeconds) {
                        break;
                    }
                    Object server_status = JMXClientUtils.getAttribute(mbean_server_status, attribute_server_status);
                    ss_status = String.valueOf(server_status);
                    if(logger.isDebugEnabled())
                        logger.debug("session server status is:{} in the {}",new Object[]{ss_status,session_server_name});
                    if (String.valueOf(server_status).equalsIgnoreCase(SS_ACTIVE))
                        break;
                    
                } catch (Exception e) {
                    if (logger.isTraceEnabled()) {
                        logger.trace("Get attribute " + attribute_server_status + " from " + mbean_server_status
                                + " is failed!");
                    }
                    ss_status = "IDEL";
                }  
            }
            try {
                ssRow.put("server_status", ss_status);
                ssRow.remove("state");
                logger.debug("session server state is:{}",ssRow.toString());

            } catch (JSONException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            countNum++;
        }
    }
}
